package com.xbongbong.pro.message.service.impl;/*/*/

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.message.domain.entity.PushSetEntity;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.entity.OperateLogEntity;
import com.xbongbong.paas.log.model.OperateLogModel;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.factory.MessageSetServiceFactory;
import com.xbongbong.pro.message.model.PushSetModel;
import com.xbongbong.pro.message.pojo.MessageMenuPojo;
import com.xbongbong.pro.message.pojo.dto.MessageSetDetailDTO;
import com.xbongbong.pro.message.pojo.dto.MessageSetEnableDTO;
import com.xbongbong.pro.message.pojo.dto.MessageSetMenuListDTO;
import com.xbongbong.pro.message.pojo.dto.MessageSetSaveDTO;
import com.xbongbong.pro.message.pojo.vo.MessageSetDetailVO;
import com.xbongbong.pro.message.pojo.vo.MessageSetEnableVO;
import com.xbongbong.pro.message.pojo.vo.MessageSetMenuListVO;
import com.xbongbong.pro.message.pojo.vo.MessageSetSaveVO;
import com.xbongbong.pro.message.service.MessageSetService;
import com.xbongbong.pro.message.service.ParentMessageSetService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.CompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * Description: 消息设置相关的具体实现
 *
 * @author 魏荣杰
 * @version v1.0
 * @date 2019/1/4 9:57
 * @since v1.0
 */
@Service("messageSetService")
public class MessageSetServiceImpl implements ParentMessageSetService {

    private static final Logger LOG = LoggerFactory.getLogger(MessageSetServiceImpl.class);

    @Resource
    private PushSetModel pushSetModel;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private LogHelp logHelp;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private OperateLogModel operateLogModel;
    @Resource
    private MessageSetServiceFactory messageSetServiceFactory;

    @Override
    public MessageSetMenuListVO getMenuList(MessageSetMenuListDTO messageSetMenuListDTO) throws XbbException {
        MessageSetMenuListVO messageSetMenuListVO = new MessageSetMenuListVO();
        try {
            PaasAppEntity paasAppEntity = paasAppModel.getByKey(messageSetMenuListDTO.getAppId(), messageSetMenuListDTO.getCorpid());
            messageSetMenuListDTO.setAlias(paasAppEntity.getAlias());
            MessageSetService abstractMessageSetService = messageSetServiceFactory.getMessageSetService(paasAppEntity.getAlias());
            if (Objects.nonNull(abstractMessageSetService)) {
                return abstractMessageSetService.getMenuList(messageSetMenuListDTO);
            }
            if (Objects.equals(messageSetMenuListDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                PaasAppEntity appEntity = paasAppModel.getByKey(messageSetMenuListDTO.getAppId(), messageSetMenuListDTO.getCorpid());
                List<MessageMenuPojo> menu = new ArrayList<>();
                messageSetMenuListVO.setMenuList(menu);
            } else if (Objects.equals(messageSetMenuListDTO.getSaasMark(), SaasMarkEnum.PAAS.getCode())) {
                // TODO message

            } else {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, SystemErrorCodeEnum.API_ERROR_100028.getMsg());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("获取系统设置消息菜单失败");
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return messageSetMenuListVO;
    }

    @Override
    public MessageSetDetailVO getSetDetailList(MessageSetDetailDTO messageSetDetailDTO) throws XbbException {
        MessageSetDetailVO messageSetDetailVO = new MessageSetDetailVO();
        UserVO loginUser = messageSetDetailDTO.getLoginUser();
        if (!ProPermissionHelp.hasPermission(loginUser, ProPermissionAliasEnum.PUSH_SET_VIEW.getAlias())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
        }
        try {
            PaasAppEntity paasAppEntity = paasAppModel.getByKey(messageSetDetailDTO.getAppId(), messageSetDetailDTO.getCorpid());
            MessageSetService abstractMessageSetService = messageSetServiceFactory.getMessageSetService(paasAppEntity.getAlias());
            if (Objects.nonNull(abstractMessageSetService) && Objects.equals(messageSetDetailDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                return abstractMessageSetService.getSetDetailList(messageSetDetailDTO);
            } else if (Objects.equals(messageSetDetailDTO.getSaasMark(), SaasMarkEnum.PAAS.getCode())){

            }
            /*if (Objects.equals(messageSetDetailDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                List<MessageSetDetailPojo> detailPojoList = messageSetHelper.getMessageSetSaasDetailList(messageSetDetailDTO);
                messageSetDetailVO.setDetailList(detailPojoList);
            } else if (Objects.equals(messageSetDetailDTO.getSaasMark(), SaasMarkEnum.PAAS.getCode())) {
                // TODO message
            } else {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, SystemErrorCodeEnum.API_ERROR_100028.getMsg());
            }*/
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("获取消息设置详情失败");
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return messageSetDetailVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MessageSetSaveVO saveMessageSet(MessageSetSaveDTO messageSetSaveDTO) throws XbbException {
        MessageSetSaveVO messageSetSaveVo = new MessageSetSaveVO();
        UserVO loginUser = messageSetSaveDTO.getLoginUser();
        Set<String> permSet = loginUser.getPermSet();
        if (Objects.isNull(permSet) || !permSet.contains(ProPermissionAliasEnum.PUSH_SET_UPDATE.getAlias())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
        }
        try {
            PaasAppEntity paasAppEntity = paasAppModel.getByKey(messageSetSaveDTO.getAppId(), messageSetSaveDTO.getCorpid());
            MessageSetService abstractMessageSetService = messageSetServiceFactory.getMessageSetService(paasAppEntity.getAlias());
            if (Objects.nonNull(abstractMessageSetService)) {
                return abstractMessageSetService.saveMessageSet(messageSetSaveDTO);
            }
            if (Objects.equals(messageSetSaveDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                //saas
                Long id = messageSetSaveDTO.getId();
                PushSetEntity pushSetEntity = new PushSetEntity();
                PushSetEntity oldPushSetEntity = null;
                if (Objects.equals(id, 0L)) {
                    //新建
                    pushSetEntity = new PushSetEntity();
                    pushSetEntity.setCorpid(messageSetSaveDTO.getCorpid());
                    pushSetEntity.setAttrEntity(messageSetSaveDTO.getAttrEntity());
                    pushSetEntity.setType(messageSetSaveDTO.getType());
                    pushSetEntity.setSubType(messageSetSaveDTO.getSubType());
                    pushSetEntity.setEnable(messageSetSaveDTO.getEnable());
                    pushSetEntity.setRefEntity(messageSetSaveDTO.getRefEntity());
                    pushSetEntity.setTemplateId(messageSetSaveDTO.getTemplateId());
                } else {
                    //编辑
                    oldPushSetEntity = pushSetModel.getByKey(messageSetSaveDTO.getId(), messageSetSaveDTO.getCorpid());
                    if (oldPushSetEntity == null) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, SystemErrorCodeEnum.API_ERROR_100018.getMsg());
                    }
                    BeanUtil.copyProperties(oldPushSetEntity, pushSetEntity);
                }
                pushSetEntity.setPushObject(messageSetSaveDTO.getPushObject());
                pushSetEntity.setPushTime(messageSetSaveDTO.getPushTime());
                messageSetSaveVo.setId(pushSetModel.save(pushSetEntity));

                if (Objects.equals(pushSetEntity.getEnable(), 1)) {
                    CompanyEntity companyEntity = companyModel.getByKey(messageSetSaveDTO.getCorpid());
                    companyEntity.setIsPushMessage(1);
                    companyModel.update(companyEntity);
                }

                // 日志
                PushTypeEnum pushTypeEnum = PushTypeEnum.getPushTypeByCodeAndSubCode(pushSetEntity.getType(), pushSetEntity.getSubType());
                String memo;
                if (Objects.equals(id, 0L)) {
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.MESSAGE_PUSH_SET_LOG_MEMO_ADD_SET), messageSetSaveDTO.getLoginUserName(), pushTypeEnum.getName());
                    OperateLogEntity logEntity = new OperateLogEntity(messageSetSaveDTO.getCorpid(), messageSetSaveDTO.getUserId(), messageSetSaveDTO.getLoginUserName(), OperateModuleTypeEnum.MESASAGE_PUSH_SET,
                            OperateTypeEnum.NEW, pushSetEntity.getId().toString(), pushTypeEnum.getName(), memo, messageSetSaveDTO.getHttpHeader(), null);
                    operateLogModel.insert(logEntity);
                } else {
                    JSONObject oldObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(oldPushSetEntity));
                    JSONObject newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(pushSetEntity));

                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.MESSAGE_PUSH_SET_LOG_MEMO_EDIT_SET), messageSetSaveDTO.getLoginUserName(), pushTypeEnum.getName());
                    List<DetailLogPojo> detailArr = logHelp.getDetailArr4Normal(messageSetSaveDTO.getCorpid(), OperateModuleTypeEnum.MESASAGE_PUSH_SET, oldObj, newObj);
                    mongoLogHelp.buildLog4DetailArr(detailArr, messageSetSaveDTO.getCorpid(), messageSetSaveDTO.getUserId(), messageSetSaveDTO.getLoginUserName(), OperateModuleTypeEnum.MESASAGE_PUSH_SET, OperateTypeEnum.EDIT, id.toString(), pushTypeEnum.getName(), memo, messageSetSaveDTO.getHttpHeader());
                }

            } else if (Objects.equals(messageSetSaveDTO.getSaasMark(), SaasMarkEnum.PAAS.getCode())) {
                //paas

            } else {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, SystemErrorCodeEnum.API_ERROR_100028.getMsg());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("保存消息设置失败");
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return messageSetSaveVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MessageSetEnableVO enableMessageSet(MessageSetEnableDTO messageSetEnableDTO) throws XbbException {
        MessageSetEnableVO messageSetEnableVO = new MessageSetEnableVO();
        UserVO loginUser = messageSetEnableDTO.getLoginUser();
        Set<String> permSet = loginUser.getPermSet();
        if (Objects.isNull(permSet) || !permSet.contains(ProPermissionAliasEnum.PUSH_SET_UPDATE.getAlias())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
        }
        try {
            PaasAppEntity paasAppEntity = paasAppModel.getByKey(messageSetEnableDTO.getAppId(), messageSetEnableDTO.getCorpid());
            MessageSetService abstractMessageSetService = messageSetServiceFactory.getMessageSetService(paasAppEntity.getAlias());
            if (Objects.nonNull(abstractMessageSetService)) {
                return abstractMessageSetService.enableMessageSet(messageSetEnableDTO);
            }
            if (Objects.equals(messageSetEnableDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                PushSetEntity pushSetEntity = pushSetModel.getByKey(messageSetEnableDTO.getId(), messageSetEnableDTO.getCorpid());
                if (pushSetEntity == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, SystemErrorCodeEnum.API_ERROR_100018.getMsg());
                }
                pushSetEntity.setEnable(messageSetEnableDTO.getEnable());
                messageSetEnableVO.setId(pushSetModel.save(pushSetEntity));

                // 日志
                PushTypeEnum pushTypeEnum = PushTypeEnum.getPushTypeByCodeAndSubCode(pushSetEntity.getType(), pushSetEntity.getSubType());
                OperateTypeEnum operateTypeEnum = (Objects.equals(BasicConstant.NO_USE, messageSetEnableDTO.getEnable())) ? OperateTypeEnum.CLOSE : OperateTypeEnum.ENABLE;
                String enableStr = (Objects.equals(BasicConstant.NO_USE, messageSetEnableDTO.getEnable())) ? EnableEnum.CLOSE.getMemo() : EnableEnum.OPEN.getMemo();
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.MESSAGE_PUSH_SET_LOG_MEMO_ENABLE), messageSetEnableDTO.getLoginUserName() + enableStr, pushTypeEnum.getName());
                OperateLogEntity logEntity = new OperateLogEntity(messageSetEnableDTO.getCorpid(), messageSetEnableDTO.getUserId(), messageSetEnableDTO.getLoginUserName(), OperateModuleTypeEnum.MESASAGE_PUSH_SET,
                        operateTypeEnum, pushSetEntity.getId().toString(), pushTypeEnum.getName(), memo, messageSetEnableDTO.getHttpHeader(), null);
                operateLogModel.insert(logEntity);
            } else if (Objects.equals(messageSetEnableDTO.getSaasMark(), SaasMarkEnum.PAAS.getCode())) {
                //paas

            } else {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, SystemErrorCodeEnum.API_ERROR_100028.getMsg());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("开关消息设置失败");
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return messageSetEnableVO;
    }


}
